# -*- coding: utf-8 -*-
""" Security functions """
from uuid import uuid5, NAMESPACE_DNS
from cPickle import dumps
from hashlib import md5

__all__ = ['md5sum', 'securityid', 'roles']
__author__ = 'Sergey Sobko, Timir Nureev'
__copyright__ = 'Copyright (c) 2010, DEKO PROFIT (The ProfitWare Project)'
__license__ = 'BSD'
__credits__ = ['Sergey Sobko', 'Timir Nureev']
__email__ = 'info@dekoprofit.ru'
__status__ = 'Prototype'

secret = 'hello'
domain = 'dcs.profitware.ru'

md5sum = lambda x: md5(x).hexdigest()
securityid = lambda obj: uuid5(NAMESPACE_DNS, md5sum(dumps(obj)) + '.%(secret)s.%(domain)s' % {'secret': secret, 'domain': domain})

__all__ = ['roles']

__rolebit = lambda x: 1 << x

ROLES_ANYBODY = 0
ROLES_REGISTERED = __rolebit(0)
ROLES_ANONYMOUS = __rolebit(1)
ROLES_MODERATOR = __rolebit(2) | ROLES_REGISTERED
ROLES_SPECIAL1 = __rolebit(3) | ROLES_REGISTERED
ROLES_SPECIAL2 = __rolebit(4) | ROLES_REGISTERED
ROLES_SPECIAL3 = __rolebit(5) | ROLES_MODERATOR | ROLES_REGISTERED
ROLES_ADMIN = __rolebit(6) | ROLES_SPECIAL1 | ROLES_SPECIAL2 | ROLES_MODERATOR | ROLES_REGISTERED


class roles(dict):
    hasrole = 0
    inrole = lambda self, objref: self.has_key(objref) and self.hasrole & self[objref] == self[objref] or False
    def __init__(self, hasrole = 0, roledict = {}):
        """ hasrole - roles user has, roledict - dict of objects indentified by unique ids"""
        self.update(roledict)
        self.hasrole = hasrole

